package br.com.async.infrastructure.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import br.com.async.domain.room.Room;
import br.com.async.domain.room.RoomRepository;
import br.com.async.domain.room.RoomStatus;
import br.com.async.infrastructure.AbstractRepositoryImpl;
import br.com.async.util.ResponseData;

public class RoomRepositoryImpl extends AbstractRepositoryImpl<Room, Integer> implements RoomRepository{

	public RoomRepositoryImpl() {
		super(Room.class);
	}
	
	public ResponseData<Room> listRoomByCriterions(String name, RoomStatus roomStatus, String categoryCode, Integer offset, Integer maxResult){
		
		ResponseData<Room> rd = new ResponseData<Room>();
		Criteria criteria = getSession().createCriteria(Room.class);
		
		criteria.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
		
		if(roomStatus != null)
			criteria.add(Restrictions.eq("roomStatus", roomStatus));
		
		if(categoryCode != null){
			criteria.createAlias("category", "c");
			
			if(Integer.parseInt(categoryCode) != 0){
				Criterion c1 = Restrictions.eq("c.code",Integer.parseInt(categoryCode));
				criteria.add(c1);
			}
		}
		
		rd.setQuantityRowsFromQuery(criteria.list().size());
		System.out.println("Tamano da lista "+ criteria.list().size());
		
		criteria.setMaxResults(maxResult);
		criteria.setFirstResult(offset);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.addOrder(Order.asc("code"));
		
		rd.setItems((List<Room>)criteria.list());
	
		return rd;
	}

	

}
